package com.xuhuan.juc.safedemo;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author huan.xu
 * @Date 2021/12/29 10:21
 * @Description list不安全案例
 */
public class ListNotSafeDemo {
    public static void main(String[] args) {

    }

    /**
     * map不安全演示
     */
    private static void mapNotSafe() {
        //        Map<String, String> map = new HashMap<>();
//        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, "线程" + i).start();
        }
    }

    /**
     * set不安全演示
     */
    private static void setNotSafe() {
        //        Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, "线程" + i).start();
        }
    }

    /**
     * list不安全演示
     */
    private static void listNotSafe() {
        List<String> list = new ArrayList<>();
//        List<String> list = new Vector<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
//        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, "线程" + i).start();
        }
    }
}
